package com.midongtech.cpd.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.WebSettings;

import androidx.annotation.NonNull;

import com.midongtech.cpd.constants.SpConstant;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;

public class DeviceUtil {

    private static final String TAG = "DeviceUtil";

    private static final String marshmallowMacAddress = "02:00:00:00:00:00";
    private static final String fileAddressMac = "/sys/class/net/wlan0/address";

    public static String getDeviceId(Context context) {
        String id = PreferencesUtils.getInstance(context).getString(SpConstant.SP_IMEI);
        if (!TextUtils.isEmpty(id)) {
            return id;
        }
        //android.telephony.TelephonyManager
        try {
            TelephonyManager mTelephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            if (mTelephony != null && mTelephony.getDeviceId() != null) {
                id = mTelephony.getDeviceId();
            } else {
                //android.provider.Settings;
                id = Settings.Secure.getString(context.getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);
            }
            if (!TextUtils.isEmpty(id)) {
                PreferencesUtils.getInstance(context).putString(SpConstant.SP_IMEI, id);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return id;
    }


    public static String getOaid(final Context context) {
        String oaid0 = PreferencesUtils.getInstance(context).getString(SpConstant.SP_OAID);
        if (TextUtils.isEmpty(oaid0) && context != null) {
            try {
                MiitHelper miitHelper = new MiitHelper(new MiitHelper.AppIdsUpdater() {
                    @Override
                    public void OnIdsAvailed(@NonNull String oaid, boolean isSupport) {
                        Log.e(TAG, "ids:" + oaid);
                        if (isSupport && !TextUtils.isEmpty(oaid)) {
                            PreferencesUtils preferencesUtils = PreferencesUtils.getInstance(context);
                            preferencesUtils.putString(SpConstant.SP_OAID, oaid);
                        }
                    }
                });
                miitHelper.getDeviceIds(context);
                miitHelper.getDeviceIds(context);
            } catch (Exception e) {
                e.printStackTrace();
                Log.e(TAG, "getOaid Exception:" + e.getMessage());
            }
        }
        return oaid0;
    }

    public static String getIp(final Context context) {
        String ip = "";
        ConnectivityManager conMan = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        // mobile 3G Data Network
        try {
            android.net.NetworkInfo.State mobile = conMan.getNetworkInfo(
                    ConnectivityManager.TYPE_MOBILE).getState();
            // wifi
            android.net.NetworkInfo.State wifi = conMan.getNetworkInfo(
                    ConnectivityManager.TYPE_WIFI).getState();

            // 如果3G网络和wifi网络都未连接，且不是处于正在连接状态 则为空
            if (mobile == android.net.NetworkInfo.State.CONNECTED
                    || mobile == android.net.NetworkInfo.State.CONNECTING) {
                ip = "";
            }
            if (wifi == android.net.NetworkInfo.State.CONNECTED
                    || wifi == android.net.NetworkInfo.State.CONNECTING) {
                //获取wifi服务
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                int ipAddress = wifiInfo.getIpAddress();
                ip = (ipAddress & 0xFF) + "." +
                        ((ipAddress >> 8) & 0xFF) + "." +
                        ((ipAddress >> 16) & 0xFF) + "." +
                        (ipAddress >> 24 & 0xFF);
            }
        } catch (NullPointerException e) {
        }
        return ip;
    }

    //Anroid6.0以下获取mac方法
    private static String getMacBeforeAndroidSmallow(Context context) {
        String mac = "";
        try {
            WifiManager wifiManager = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            mac = wifiInfo.getMacAddress();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mac;
    }

    public static String getMac(Context context) {
        String mac = "";
        if (Build.VERSION.SDK_INT >= 23) {
            mac = DeviceUtil.getMacAfterAndroidSmallow(context) + "";
        } else {
            mac = DeviceUtil.getMacBeforeAndroidSmallow(context) + "";
        }
        return mac;
    }

    //Anroid6.0及以上获取mac方法
    private static String getMacAfterAndroidSmallow(Context context) {
        WifiManager wifiMan = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInf = wifiMan.getConnectionInfo();

        if (wifiInf != null && marshmallowMacAddress.equals(wifiInf.getMacAddress())) {
            String result = "";
            try {
                result = getAdressMacByInterface();
                if (result != null) {
                    return result;
                } else {
                    result = getAddressMacByFile(wifiMan);
                    return result;
                }
            } catch (IOException e) {
                Log.w("MobileAccess", "Erreur lecture propriete Adresse MAC");
            } catch (Exception e) {
                Log.w("MobileAcces", "Erreur lecture propriete Adresse MAC ");
            }
        } else {
            if (wifiInf != null && wifiInf.getMacAddress() != null) {
                return wifiInf.getMacAddress();
            } else {
                return "";
            }
        }
        return marshmallowMacAddress;
    }

    private static String getAdressMacByInterface() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (nif.getName().equalsIgnoreCase("wlan0")) {
                    byte[] macBytes = nif.getHardwareAddress();
                    if (macBytes == null) {
                        return "";
                    }

                    StringBuilder res1 = new StringBuilder();
                    for (byte b : macBytes) {
                        res1.append(String.format("%02X:", b));
                    }

                    if (res1.length() > 0) {
                        res1.deleteCharAt(res1.length() - 1);
                    }
                    return res1.toString();
                }
            }

        } catch (Exception e) {
            Log.w("MobileAcces", "Erreur lecture propriete Adresse MAC ");
        }
        return null;
    }

    private static String getAddressMacByFile(WifiManager wifiMan) throws Exception {
        String ret;
        int wifiState = wifiMan.getWifiState();

//        wifiMan.setWifiEnabled(true);
        File fl = new File(fileAddressMac);
        FileInputStream fin = new FileInputStream(fl);
        ret = crunchifyGetStringFromStream(fin);
        fin.close();
        boolean enabled = WifiManager.WIFI_STATE_ENABLED == wifiState;
//        wifiMan.setWifiEnabled(enabled);
        return ret;
    }

    private static String crunchifyGetStringFromStream(InputStream crunchifyStream) throws IOException {
        if (crunchifyStream != null) {
            Writer crunchifyWriter = new StringWriter();

            char[] crunchifyBuffer = new char[2048];
            try {
                Reader crunchifyReader = new BufferedReader(new InputStreamReader(crunchifyStream, "UTF-8"));
                int counter;
                while ((counter = crunchifyReader.read(crunchifyBuffer)) != -1) {
                    crunchifyWriter.write(crunchifyBuffer, 0, counter);
                }
            } finally {
                crunchifyStream.close();
            }
            return crunchifyWriter.toString();
        } else {
            return "No Contents";
        }
    }

    /**
     * 手机厂商
     * @return
     */
    public static String getVendor() {
        return Build.BRAND;
    }

    /**
     * 手机型号
     * @return
     */
    public static String getModel() {
        return Build.MODEL;
    }

    /**
     * 安卓操作系统版本号
     * @return
     */
    public static String getOsVersion() {
        return Build.VERSION.RELEASE;
    }

    /**
     * 安卓 apiLevel
     * @return
     */
    public static int getApiLevel() {
        return Build.VERSION.SDK_INT;
    }

    public static int isRoot() {
        boolean root = false;
        try {
            if ((!new File("/system/bin/su").exists())
                    && (!new File("/system/xbin/su").exists())) {
                root = false;
            } else {
                root = true;
            }

        } catch (Exception e) {
        }
        return root?1:0;
    }

    public static String getAndroidId(Context context) {
        String androidId = PreferencesUtils.getInstance(context).getString(SpConstant.SP_ANDROIDID);
        if (TextUtils.isEmpty(androidId)) {
            try {
                androidId = Settings.Secure.getString(context.getContentResolver(),
                        Settings.Secure.ANDROID_ID);
                if (!TextUtils.isEmpty(androidId)) {
                    PreferencesUtils.getInstance(context).putString(SpConstant.SP_ANDROIDID, androidId);
                }

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return androidId;
    }

    public static String getUserAgent(Context context) {
        String userAgent = "";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            try {
                userAgent = WebSettings.getDefaultUserAgent(context);
            } catch (Exception e) {
                userAgent = System.getProperty("http.agent");
                if (TextUtils.isEmpty(userAgent))
                    userAgent = "Mozilla/5.0 (Linux; U; Android 1.1; en-gb; dream) ";
            }
        } else {
            userAgent = System.getProperty("http.agent");
        }
        //中文过滤
        StringBuffer sb = new StringBuffer();
        for (int i = 0, length = userAgent.length(); i < length; i++) {
            char c = userAgent.charAt(i);
            if (c <= '\u001f' || c >= '\u007f') {
                sb.append(String.format("\\u%04x", (int) c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }






}
